package com.mini.listener;

import cn.hutool.core.util.StrUtil;
import com.mini.redis.RedisCache;
import com.mini.ws.MyWebSocketHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private RedisCache redisCache;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        //获取过期的key
        String expireKey = message.toString();
//        log.info("失效+key:{},value:{}",expireKey,new String(pattern));

        String[] split = expireKey.split(":");

        for (String s : split) {
            if (StrUtil.equals(s,"websocket")){
                MyWebSocketHandler.close(split[2],split[3]);
            }
        }
        //这里还可以根据key的自定义前缀来判断执行哪个条件
        //......
    }
}
